package net.kazed.nextaction.tools;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import net.kazed.nextaction.R;
import net.kazed.nextaction.database.GtdProvider;
import net.kazed.nextaction.database.serialize.BackupFileSummary;
import net.kazed.nextaction.database.serialize.BackupFileSummaryQuery;
import net.kazed.nextaction.database.serialize.ParseException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Display information of backup file.
 */
public class BackupItemActivity extends Activity {

    private static final int BACKUP_DELETE = Menu.FIRST;
    private static final int BACKUP_EXPORT = BACKUP_DELETE + 1;

    private static final String TAG = "BackupItemActivity";
    
    private TextView fieldCreateDate;
    private TextView fieldNumberOfContexts;
    private TextView fieldNumberOfTasks;
    private Button mergeButton;
    private Button replaceButton;
    
    private Uri backupUri;
    private long backupId;
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.backup_item_view);
        setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);

        fieldCreateDate = (TextView) findViewById(R.id.create_date);
        fieldNumberOfContexts = (TextView) findViewById(R.id.number_of_contexts);
        fieldNumberOfTasks = (TextView) findViewById(R.id.number_of_tasks);
        
        mergeButton = (Button) findViewById(R.id.merge_button);
        mergeButton.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              AlertDialog.Builder builder = new AlertDialog.Builder(BackupItemActivity.this);
              builder.setTitle(R.string.backup_merge_alert_title).setMessage(R.string.backup_merge_alert_message)
                 .setIcon(android.R.drawable.ic_dialog_alert);
              builder.setPositiveButton(R.string.alert_yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        Log.d(TAG, "backupUri: " + backupUri);
                        try {
                            getContentResolver().update(backupUri, null, "merge", null);
                            Toast toast = Toast.makeText(BackupItemActivity.this, R.string.backup_restore_successful, Toast.LENGTH_LONG);
                            toast.show();
                            finish();
                        } catch (ParseException e) {
                            Log.e(TAG, "Merge failed", e);
                            Toast toast = Toast.makeText(BackupItemActivity.this, R.string.backup_restore_failure, Toast.LENGTH_LONG);
                            toast.show();
                        }
                    }
              });
              builder.setNegativeButton(R.string.alert_no, null);
              builder.show();
          }
        });
      
        replaceButton = (Button) findViewById(R.id.replace_button);
        replaceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(BackupItemActivity.this);
                builder.setTitle(R.string.backup_replace_alert_title).setMessage(R.string.backup_replace_alert_message)
                   .setIcon(android.R.drawable.ic_dialog_alert);
                builder.setPositiveButton(R.string.alert_yes, new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int whichButton) {
                          Log.d(TAG, "backupUri: " + backupUri);
                          try {
                              getContentResolver().update(backupUri, null, "replace", null);
                              Toast toast = Toast.makeText(BackupItemActivity.this, R.string.backup_restore_successful, Toast.LENGTH_LONG);
                              toast.show();
                              finish();
                          } catch (ParseException e) {
                              Toast toast = Toast.makeText(BackupItemActivity.this, R.string.backup_restore_failure, Toast.LENGTH_LONG);
                              toast.show();
                          }
                      }
                });
                builder.setNegativeButton(R.string.alert_no, null);
                builder.show();
            }
          });
        
        backupUri = getIntent().getData();
        backupId = Long.parseLong(backupUri.getLastPathSegment());
        
        Intent returnIntent = new Intent();
        setResult(RESULT_OK, returnIntent);
    }

    @Override
    protected void onResume() {
        super.onResume();

        Cursor cursor = null;
        try {
            Uri summaryUri = ContentUris.withAppendedId(BackupFileSummary.CONTENT_ITEM_URI, backupId);
            cursor = managedQuery(summaryUri, null, null, null, null);
            BackupFileSummaryQuery query = new BackupFileSummaryQuery(cursor);
            BackupFileSummary summary = query.getBackupFileSummary();
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            fieldCreateDate.setText(dateFormat.format(summary.getCreateDate()));
            fieldNumberOfContexts.setText(Integer.toString(summary.getNumberOfContexts()));
            fieldNumberOfTasks.setText(Integer.toString(summary.getNumberOfTasks()));
        } finally {
            if (cursor != null ) {
                cursor.close();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Resources resources = getResources();
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            menu.add(0, BACKUP_EXPORT, 0, resources.getString(R.string.menu_export_backup)).setIcon(
                            android.R.drawable.ic_menu_save).setAlphabeticShortcut('e');
        }
        MenuItem item = menu.add(0, BACKUP_DELETE, 0, resources.getString(R.string.menu_delete_backup)).setIcon(
                android.R.drawable.ic_menu_delete);
        item.setAlphabeticShortcut('d');
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case BACKUP_DELETE:
            AlertDialog.Builder builder = new AlertDialog.Builder(BackupItemActivity.this);
            builder.setTitle(R.string.backup_delete_alert_title).setMessage(R.string.backup_delete_alert_message)
               .setIcon(android.R.drawable.ic_dialog_alert);
            builder.setPositiveButton(R.string.alert_yes, new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                      Log.d(TAG, "backupUri: " + backupUri);
                      getContentResolver().delete(backupUri, null, null);
                      finish();
                  }
            });
            builder.setNegativeButton(R.string.alert_no, null);
            builder.show();
            break;
        case BACKUP_EXPORT:
            try {
                getContentResolver().update(backupUri, null, GtdProvider.BACKUP_SAVE_TO_SD_CARD, null);
                Toast toast = Toast.makeText(BackupItemActivity.this, R.string.backup_export_successful, Toast.LENGTH_LONG);
                toast.show();
            } catch (RuntimeException e) {
                Log.e(TAG, "export failed", e);
                Toast toast = Toast.makeText(BackupItemActivity.this, R.string.backup_export_failure, Toast.LENGTH_LONG);
                toast.show();
            }
            break;
        }
        return super.onOptionsItemSelected(item);
    }
    
}